from flask import request, Blueprint
from flask_restful import Api, Resource
from models.init_sqlalchemy import db
from models.models import Ranks
import uuid
from flask_jwt_extended import jwt_required
from utils.h_result import HResult

bp = Blueprint('ranks', __name__, url_prefix='/ranks/')

class AddRank(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        name = data.get('name')
        
        if not name:
            return HResult().get_result('error', '参数错误!')
            
        rank = Ranks(
            id=str(uuid.uuid4()),
            name=name
        )
        
        if 'style' in data:
            rank.style = data['style']
            
        db.session.add(rank)
        db.session.commit()
        return HResult().get_result('success', '头衔添加成功!')

class DeleteRank(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        rank_ids = data['ids']
        
        for rank_id in rank_ids:
            rank = Ranks.query.filter_by(id=rank_id).first()
            if rank:
                db.session.delete(rank)
                
        db.session.commit()
        return HResult().get_result('success', '删除成功!')

class UpdateRank(Resource):
    method_decorators = [jwt_required()]
    
    def post(self):
        data = request.get_json()
        rank_id = data['id']
        rank_data = data['rank']
        
        rank = Ranks.query.filter_by(id=rank_id).first()
        if not rank:
            return HResult().get_result('error', '头衔不存在!')
            
        for key, value in rank_data.items():
            if key != 'id':
                setattr(rank, key, value)
        
        db.session.commit()
        return HResult().get_result('success', '修改成功!')

class RankInfo(Resource):
    method_decorators = [jwt_required()]
    
    def get(self):
        rank_id = request.args.get('id')
        rank = Ranks.query.filter_by(id=rank_id).first()
        
        if not rank:
            return HResult().get_result('error', '头衔不存在!')
            
        data = rank.to_dict()
        # 添加使用该头衔的用户列表
        data['users'] = [user.to_dict() for user in rank.user]
            
        return HResult().get_result('success', data=data)

class QueryAllRanks(Resource):
    method_decorators = [jwt_required()]
    
    def get(self):
        ranks = Ranks.query.all()
        return HResult().get_result('success', data=[rank.to_dict() for rank in ranks])

api = Api(bp)
api.add_resource(AddRank, '/add/', endpoint='add')
api.add_resource(DeleteRank, '/delete/', endpoint='delete')
api.add_resource(UpdateRank, '/update/', endpoint='update')
api.add_resource(RankInfo, '/info/', endpoint='info')
api.add_resource(QueryAllRanks, '/list/', endpoint='list') 